﻿using HZY.Framework.DependencyInjection;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Apple.SprayingProcessSystem
{
    public partial class PageEquipmentMonitor2 : UIPage, ISingletonSelfDependency
    {
        private List<Control> controls;

        private CancellationTokenSource cts = new CancellationTokenSource();

        public PageEquipmentMonitor2()
        {
            InitializeComponent();

            controls = Globals.GetAllControls(this);

            this.Load += PageEquipmentMonitor2_Load;

            this.Closed += (s, e) =>
            {
               // 取消刷新任务
                cts.Cancel();
            };
        }

        private void PageEquipmentMonitor2_Load(object? sender, EventArgs e)
        {
            Task.Run(async () => await ControlRefresh(), cts.Token);
        }

        private async Task ControlRefresh()
        {
            while (true)
            {
                if (!cts.IsCancellationRequested)
                {
                    if (Globals.SiemensClient == null || !Globals.SiemensClient.Connected)
                    {
                        continue;
                    }

                    this.Invoke(() =>
                    {
                        foreach (Control control in controls)
                        {
                            if (control is UserDeviceState userDeviceState)
                            {
                                userDeviceState.State = Globals.DataDic[userDeviceState.VariableName].ToString() == "1";
                            }
                            else if (control is UserVarCurrentValue userVarCurrentValue)
                            {
                                userVarCurrentValue.VarValue = Globals.DataDic[userVarCurrentValue.VariableName].ToString().ToFloat();
                            }
                            else if (control is UserAlarmState userAlarmState)
                            {
                                userAlarmState.State = Globals.DataDic[userAlarmState.VariableName].ToString() != "1";
                            }
                        }
                    });
                    await Task.Delay(500, cts.Token);
                }
            }
        }

        #region 窗体切换卡顿处理
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams paras = base.CreateParams;
                paras.ExStyle |= 0x02000000;
                return paras;
            }
        }
        #endregion
    }
}
